import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'

import {users} from './data/user'

export default {
  init () {
    let mock = new MockAdapter(axios)
    // 模拟成功请求
    mock.onGet('/success').reply(200, {
      msg: 'success'
    })
    // 模拟失败请求
    mock.onGet('/error').reply(500, {
      msg: 'false'
    })
    // 模拟登陆接口
    mock.onPost('/login').reply(config => {
      // 解析axios传来的数据
      let {username, password} = JSON.parse(config.data)
      return new Promise((resolve) => {
        let token = ''
        let hasUser = users.some(u => {
          if (u.username === username && u.password === password) {
            token = u.token
            return true
          }
        })
        if (hasUser) {
          resolve([200, {code: 200, msg: '请求成功', token: token}])
        } else {
          resolve([200, {code: 500, msg: '账号或密码错误'}])
        }
      })
    })
    mock.onPost('/logout').reply(config => {
      let username = config.data
      return new Promise((resolve) => {
        if (username) {
          resolve([200, {code: 200, msg: '登出成功'}])
        }
      })
    })
    mock.onPost('/userinfo').reply(config => {
      let token = config.data
      return new Promise((resolve) => {
        let user = {
          uid: -1,
          username: '',
          role: {
            rolename: '',
            permissions: []
          },
          token: ''
        }
        let hasUser = users.some(u => {
          if (u.token === token) {
            user.uid = u.uid
            user.username = u.username
            user.role.rolename = u.role.rolename
            user.role.permissions = user.role.permissions.concat(u.role.permissions)
            return true
          }
        })
        if (hasUser) {
          resolve([200, {code: 200, msg: '用户数据请求成功', userInfo: user}])
        } else {
          resolve([200, {code: 500, msg: '用户数据请求失败'}])
        }
      })
    })
  }
}
